package com.zengqingfa.shardingjdbc.demo.sharding.complex;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import java.util.Collection;
import java.util.Map;

/**
 *
 * @fileName: ShardingDatabaseComplexAlgorithm
 * @author: zengqf3
 * @date: 2021-3-28 21:40
 * @description: 分库算法
 */
@Slf4j
public class ShardingDatabaseComplexAlgorithm implements ComplexKeysShardingAlgorithm<String> {

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames,
            ComplexKeysShardingValue<String> shardingValue) {
        Map<String, Collection<String>> columnNameAndShardingValuesMap = shardingValue
                .getColumnNameAndShardingValuesMap();
        log.info("columnNameAndShardingValuesMap:{}", JSON.toJSONString(columnNameAndShardingValuesMap));
        if (columnNameAndShardingValuesMap.containsKey("tenant_code") && columnNameAndShardingValuesMap
                .containsKey("id")) {
            Collection<String> tenant_code = columnNameAndShardingValuesMap.get("tenant_code");
            Collection<String> idCol = columnNameAndShardingValuesMap.get("id");
            String tenantCode = String.valueOf(tenant_code.iterator().next());
            String id = String.valueOf(idCol.iterator().next());
            long tenant_code_mod = Math.abs((tenantCode.hashCode() + id.hashCode()) % 2 + 1);
            for (String databaseName : availableTargetNames) {
                if (databaseName.endsWith(String.format("%02d", tenant_code_mod))) {
                    log.info("databaseName:{}", databaseName);
                    return Lists.newArrayList(databaseName);
                }
            }
        }
        // throw new UnsupportedOperationException();
        return Lists.newArrayList(availableTargetNames);
    }
}
